package com.kelvin.oocl.testTransaction.tool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.commons.dbcp2.BasicDataSource;


public class DBUtils {
	private static String username = "root";
	private static String pwd = "mysql";
	private static String url="jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf-8";
	private static String driver = "com.mysql.jdbc.Driver";
	private static BasicDataSource ds;
	
	private static ThreadLocal<Connection> tl = new ThreadLocal<>();
	
	static {
		ds = new BasicDataSource();
		ds.setUrl(url);
		ds.setPassword(pwd);
		ds.setUsername(username);
		ds.setDriverClassName(driver);
	}
	
	public static Connection getConnection(){
		Connection connection = tl.get();
		if(connection==null){
			try {
				connection = ds.getConnection();
				tl.set(connection);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return connection;
	}
	
	public static void close(PreparedStatement ps,Connection connection){
		try {
			if(null!=ps){
				ps.close();
			}
			if(null!=connection){
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void remove(){
		tl.remove();
	}
	
	public static void main(String[] args) {
		System.out.println(getConnection());
	}
}
